//
//  WXApiModule.swift
//  mlz
//
//  Created by 吕凌 on 2018/4/20.
//  Copyright © 2018年 吕凌. All rights reserved.
//

import Foundation

public extension WXWeixinApiModule {
    
    @objc public func sendWebpage(_ params: Dictionary<String, AnyObject>, callback: WXModuleKeepAliveCallback?) {
        let message:WXMediaMessage = WXMediaMessage()
        if (params["title"] != nil) {
            message.title = params["title"] as! String
        }
        if (params["description"] != nil) {
            message.description = params["description"] as! String
        }
        if (params["thumbUrl"] != nil) {
            let data: NSData? = NSData(contentsOf: URL(string: params["thumbUrl"] as! String)!)
            let image: UIImage? = UIImage(data: data! as Data)
            message.setThumbImage(image!)
        }
        let webpageObj:WXWebpageObject = WXWebpageObject()
        webpageObj.webpageUrl = params["url"] as! String
        message.mediaObject = webpageObj
        let req:SendMessageToWXReq = SendMessageToWXReq.init()
        req.bText = false
        req.message = message
        req.scene = params["scene"] as! Int32
        let flag = WXApi.send(req)
        callback?(flag, false)
    }
    
    @objc public func sendTimeline(_ params: Dictionary<String, AnyObject>, callback: WXModuleKeepAliveCallback?) {
        let array_photo:NSArray = params["images"] as! NSArray
        if(array_photo.count > 1) {
            self.sendTimelineWithIosShare(array_photo, callback: callback)
        } else {
            //使用微信分享api进行分享
            self.send(params, scene: Int32(WXSceneTimeline.rawValue), callback: callback)
        }
    }
    
    @objc private func sendTimelineWithIosShare(_ array_photo: NSArray, callback: WXModuleKeepAliveCallback?) {
        let array:NSMutableArray = NSMutableArray.init()
        for i in 0..<array_photo.count {
            do {
                let url = array_photo[i]
                let data: NSData? = NSData(contentsOf: URL(string: url as! String)!)
                if (data == nil) {
                    continue
                }
                let image: UIImage? = UIImage(data: data! as Data)
                let path_sandox = NSHomeDirectory()
                let imagePath = path_sandox + ("/Documents/ShareWX\(i).jpg")
                try UIImagePNGRepresentation(image!)?.write(to: URL(fileURLWithPath: imagePath))
                let shareobj:URL = URL(fileURLWithPath: imagePath)
                /** 这里做个解释 imagerang : UIimage 对象  shareobj:NSURL 对象 这个方法的实际作用就是 在调起微信的分享的时候
                 传递给他 UIimage对象,在分享的时候 实际传递的是 NSURL对象 达到我们分享九宫格的目的 */
                let item:SharedItem = SharedItem(data: image, andFile: shareobj)
                array.add(item)
            } catch let err as NSError {
                err.description
            }
        }
        let activityViewController = UIActivityViewController(activityItems: array as! [Any], applicationActivities: nil)
        //尽量不显示其他分享的选项内容
        activityViewController.excludedActivityTypes = [.postToFacebook, .postToTwitter, .postToWeibo, .message, .mail, .print, .copyToPasteboard, .assignToContact, .saveToCameraRoll, .addToReadingList, .postToFlickr, .postToVimeo, .postToTencentWeibo, .airDrop, .openInIBooks]
        self.weexInstance.viewController.present(activityViewController, animated: true, completion: nil)
        callback?(true, false)
    }
    
    @objc public func sendSession(_ params: Dictionary<String, AnyObject>,  callback: @escaping WXModuleKeepAliveCallback) {
        self.send(params, scene: Int32(WXSceneSession.rawValue), callback: callback)
    }
    
    @objc private func send(_ params: Dictionary<String, AnyObject>, scene:Int32,  callback: WXModuleKeepAliveCallback?) {
        let req:SendMessageToWXReq = SendMessageToWXReq.init()
        if(params["text"] != nil) {
            req.text = params["text"] as! String
            req.bText = true
        }
        if(params["images"] != nil) {
            let images:NSArray = params["images"] as! NSArray
            if(images.count > 0) {
                let message:WXMediaMessage = WXMediaMessage()
                let data: NSData? = NSData(contentsOf: URL(string: (images[0]) as! String)!)
                if (data != nil) {
//                    message.setThumbImage(UIImage(named: "image.png")!)
                    let imageObject:WXImageObject = WXImageObject()
                    imageObject.imageData = data! as Data
                    message.mediaObject = imageObject
                    req.message = message
                    req.bText = false
                }
            }
        }
        req.scene = scene
        let flag = WXApi.send(req)
        callback?(flag, false)
    }
    
    @objc public func sendAuth(_ params: Dictionary<String, AnyObject>,  callback: WXModuleKeepAliveCallback?) {
        let req:SendAuthReq = SendAuthReq.init()
        req.state = params["state"] as! String
        req.scope = "snsapi_userinfo"
        let flag = WXApi.send(req)
        callback?(flag, false)
    }
}
